
const fs = require('fs-extra')
const shell = require('shelljs')
const moment = require('moment')
const utils = require('../../lib/utils')
const print = require('../../lib/print')
const loading = require('ora')()

/*
 * 配置文件格式：{codePath: '', businessLines: [], devBranch: []}  
 * - codePath: 代码仓库地址
 * - businessLines: 开发的业务线
 * - devBranch: 开发的分支
 */                
let _configInfo = utils.readConfigFile('git_log.config.json', {codePath: '', businessLines: [], devBranch: []})
// 临时日志文件，放在桌面
let _tempLogFile = `${utils.getDesktopPath()}/temp-git-log-${moment().format('YYYY-MM-DD')}`

module.exports = function () {
    try {
        loading.start('log 检查中...')
        let codePath = _configInfo.codePath
        let businessLines = _configInfo.businessLines
        let devBranch = _configInfo.devBranch
        if (fs.existsSync(_tempLogFile)) {
            fs.removeSync(_tempLogFile)
        }
        fs.createFileSync(_tempLogFile)

        for (let index in businessLines) {
            let _business = businessLines[index]
            shell.cd(`${codePath}/${_business}`)
            for (let idx in devBranch) {
                gitLogCommand(devBranch[idx], _business)
            }
        }
        loading.stop()
        console.log('√√ 检查完毕')
    } catch (error) {
        loading.stop()
        print.errorLog(error)
    }
}

/*
 * 执行当天的 git log 结果写入桌面临时文件中
 * 直接打印在终端会与其他命令混合，不利于区分，因此单独写入一个文件中
 */
function gitLogCommand(branch, business) {
    // 列举当前业务线的所有分支
    let business_all_branchs = shell.exec('git branch', {silent: true})
    if (business_all_branchs.toString().indexOf(branch) !== -1) { // 包含入参分支
        // 记录原分支
        let ori_branch = shell.exec('git rev-parse --abbrev-ref HEAD', {silent: true})
        // 切换到操作分支
        shell.exec(`git checkout ${branch}`, {silent: true})
        // 当天 0 点时间格式
        let day_start = moment().startOf('day').format('YYYY-MM-DD HH:mm:ss')
        let logs = shell.exec(`git log --no-merges --author='yaqiang.cao' --date=format:'%Y-%m-%d %H:%M:%S' --since="${day_start}"`, {silent: true})
        if (logs.length) {
            fs.appendFileSync(_tempLogFile, `***** ${business} ${branch} *****`)
            fs.appendFileSync(_tempLogFile, '\n\n')
            fs.appendFileSync(_tempLogFile, logs.toString())
            fs.appendFileSync(_tempLogFile, '\n\n')
        }
        // 完成操作，切换到原分支
        shell.exec(`git checkout ${ori_branch}`, {silent: true})
    }
}

